uniform sampler2D splatTex, dirtTex, grassTex, sandTex, rockTex;
uniform float stepSize;
varying vec3 normal;
varying vec3 lightDir;

void main(void) {
    float grassWeight = texture2D(splatTex, gl_TexCoord[0].st).g;
    float sandWeight = texture2D(splatTex, gl_TexCoord[0].st).r;
    float rockWeight = texture2D(splatTex, gl_TexCoord[0].st).b;
    float dirtWeight = max(1.0-grassWeight-sandWeight-rockWeight, 0.0);

    vec2 texturePos = vec2(mod(gl_TexCoord[0].s, stepSize)/stepSize, mod(gl_TexCoord[0].t, stepSize)/stepSize);
    vec4 dirt = dirtWeight*texture2D(dirtTex, texturePos);
    vec4 grass = grassWeight*texture2D(grassTex, texturePos);
    vec4 sand = sandWeight*texture2D(sandTex, texturePos);
    vec4 rock = rockWeight*texture2D(rockTex, texturePos);
    vec4 Am = vec4(max(grass, max(sand, max(rock, dirt))).rgb,1.0);
    vec4 Dm = Am;

    normal = normalize(normal);
    lightDir = normalize(lightDir);
    float lambertTerm = dot(normal, lightDir);

    vec4 ambient = Am*gl_LightSource[0].ambient + Am*gl_LightModel.ambient;
    vec4 diffuse = Dm*gl_LightSource[0].diffuse*lambertTerm;

    vec4 fogColour = vec4(0.3, 0.3, 0.3, 1.0);
    float z = gl_FragCoord.z / gl_FragCoord.w;
    float fogFactor = exp(-0.003*z);
    fogFactor = clamp(fogFactor, 0.0, 1.0);
    gl_FragColor = mix(fogColour, ambient+diffuse, fogFactor);
    //gl_FragColor = ambient + diffuse;
}
